<template>
  <div :class="$style.paper">
    <div :class="$style.topo"></div>
  </div>
</template>
<script>
import api from '../../../common/js/api';
import { Topology } from '@topology/core';
import transformData from './../../../common/js/transform-view-data.js';
import { randomString } from './../../../common/js/utils.js';

const renderTopo = (canvas, viewJson, domId, fn) => {
  const rectObj = document.getElementById(domId).getBoundingClientRect();
  const scaleWidth = parseInt(rectObj.width) / parseInt(viewJson.data.width);
  const scaleHeight = parseInt(rectObj.height) / parseInt(viewJson.data.height);
  const scale = scaleWidth > scaleHeight ? scaleHeight : scaleWidth;
  viewJson.data.scale = scale;
  canvas.open(viewJson);
  canvas.lock(2);
  canvas.resize({
    width: viewJson.data.width * scale,
    height: viewJson.data.height * scale
  });
  canvas.scaleTo(scale);

  const translateX = parseInt(viewJson.data.width) * (scale - 1);
  const translateY = parseInt(viewJson.data.height) * (scale - 1);
  canvas.translate((translateX) / 2, translateY / 2);
  canvas.data.data.translateX = (translateX) / 2;
  canvas.data.data.translateY = (translateY) / 2;
  // if (scaleWidth > scaleHeight) {
  //   let extTranslateX = parseInt(viewJson.data.width) * scale - rectObj.width;
  //   canvas.translate((translateX - extTranslateX) / 2, translateY / 2);
  // } else {
  //   let extTranslateY = parseInt(viewJson.data.height) * scale - rectObj.height;
  //   canvas.translate(translateX / 2, (translateY - extTranslateY) / 2);
  // }
  let bgNode = canvas.data.pens.find(pen => {
    return pen.isBg;
  });
  if (bgNode) {
    canvas.bottom(bgNode);
    canvas.lockNodes([bgNode], 2);
  }
  fn && fn();
};

export default {
  name: 'PsTopo',
  data () {
    return {
      canvas: null,
      topoWrapperId: null
    };
  },
  props: {
    viewId: [String, Number]
  },
  mounted () {
    this.topoWrapperId = randomString(12, '_');
    this.$el.children[0].setAttribute('id', this.topoWrapperId);
    this.canvas = new Topology(this.topoWrapperId, { lineName: 'line' });
  },
  watch: {
    viewId: {
      immediate: true,
      handler () {
        if (this.viewId) {
          api.post('viewFlexService.getViewById', this.viewId).then(view => {
            let viewJson = transformData(JSON.parse(view.data.content));
            renderTopo(this.canvas, viewJson, this.topoWrapperId, () => {
              this.$emit('viewLoaded', this.canvas);
            });
          });
        }
      }
    }
  }
};
</script>
<style lang="scss" module>
@import './../../../style/default/ps-topo.scss';
</style>
